﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.Xml;
using WuYuHotel.SQLConn;
using WuYuHotel.Tools;
using WuYuHotel.WX_AccToken;
using System.IO;

namespace WuYuHotel.Controllers
{
    public class WxPageController : Controller
    {
        BaseDao basedao = new BaseDao();
        // GET: WxPage
        /// <summary>
        /// 错误信息页面
        /// </summary>
        /// <param name="Msg"></param>
        /// <returns></returns>
        public ActionResult ErrorPage(string Msg)
        {
            ViewBag.Msg = Msg ?? "default";
            return View("ErrorPage");
        }

        public ActionResult ZZPostMessage()
        {

            //HttpResponse output=new HttpResponse()
            System.IO.StreamReader sr = new System.IO.StreamReader(Request.InputStream,Encoding.UTF8);
            string InputDate = sr.ReadToEnd();
            sr.Close();
            sr.Dispose();
            
            System.Diagnostics.Debug.WriteLine("住哲返推送的数据:" + InputDate);
            //这个下面做一下我的事情



            try
            {
                Dictionary<string, object> pushlog = new Dictionary<string, object>();
                pushlog.Add("type", int.Parse("0"));
                pushlog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                pushlog.Add("OpID", "0");
                pushlog.Add("OpLog", "收到住哲推送数据：" +InputDate );
                basedao.save("T_LOG", pushlog);


                XmlDocument xml = new XmlDocument();
                //XmlElement element = null;
                xml.LoadXml(InputDate);
                string MessageType = (xml.SelectSingleNode("/message/head") as XmlElement).GetAttribute("serviceCode");
                //收到住哲取消订单数据，
                if (MessageType.Contains("ORDE002"))
                {
                    //收到住哲取消订单数据，
                    string HotelId = xml.SelectSingleNode("/message/body/hotelId").InnerText;
                    string OrderId = xml.SelectSingleNode("/message/body/orderId").InnerText;
                    try
                    {
                        string sql = "update t_o_order set state=2 where hotelid='" + HotelId + "' and ZZOrderId='" + OrderId + "'";
                        BaseDao.execute(sql);
                    }
                    catch (Exception ex)
                    {
                        Dictionary<string, object> datalog = new Dictionary<string, object>();
                        datalog.Add("type", int.Parse("0"));
                        datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        datalog.Add("OpID", "0");
                        datalog.Add("OpLog", "CancelOrder里面错误：" + ex.Message.ToString().Replace("'", "''").Replace(" ", ""));
                        basedao.save("T_LOG", datalog);

                    }

                }
            }
            catch (Exception ex)
            {
                Dictionary<string, object> datalog = new Dictionary<string, object>();
                datalog.Add("type", int.Parse("0"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", "0");
                datalog.Add("OpLog", "CancelOrder里面错误：" + ex.Message.ToString().Replace("'", "''").Replace(" ", ""));               
                basedao.save("T_LOG", datalog);
                datalog["OpLog"] = InputDate;
                basedao.save("T_LOG", datalog);
                return Content("true");

            }



            //以下这些东西应该可以不要，只需要返回ContentResult即可
            //System.IO.StreamWriter sw = new System.IO.StreamWriter(Response.OutputStream, Encoding.UTF8);
            //sw.Write("true");
            //sw.Flush();
            //sw.Close();
            //sw.Dispose();
            //////////////////////////////////////////////////////

            return Content("true");
            
        }

        public ActionResult MainView()
        {
            return View("MainView");
        }

        public ActionResult Index1()
        {

            string result = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (!string.IsNullOrEmpty(result))
            {
                result = result.Split(',')[0];
            }
            if (string.IsNullOrEmpty(result))
            {
                result = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            if (string.IsNullOrEmpty(result))
            {
                result = System.Web.HttpContext.Current.Request.UserHostAddress;
            }
            if (string.IsNullOrEmpty(result))
            {
                result = "0.0.0.0";
            }
            System.Diagnostics.Debug.WriteLine("页面:Index1,本次来的SessionId=" + Session.SessionID + ",time=" + DateTime.Now.ToString()+",IP="+result);
            Session["sessionId"] = Session.SessionID;
            return View("Index");
        }

        /// <summary>
        ///这里就是引导用户重新获取cookie。 
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {



            if (CheckCookies())
            {
                string result = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];


                if (string.IsNullOrEmpty(result))
                {
                    result = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
                if (string.IsNullOrEmpty(result))
                {
                    result = System.Web.HttpContext.Current.Request.UserHostAddress;
                }
                if (string.IsNullOrEmpty(result))
                {
                    result = "0.0.0.0";
                }

                try
                {
                    string openid= Request.Cookies["openid"].Value; 
                    string headurl= Request.Cookies["headimgurl"].Value;
                    string nickname = Request.Cookies["nickname"].Value;
                    string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    Dictionary<string, object> map = new Dictionary<string, object>()
                    {
                        ["openid"] = openid,
                        ["headurl"] = headurl,
                        ["nickname"] = HttpUtility.UrlDecode(nickname),
                        ["visittime"]=time,
                        ["ip"] = result
                    };
                    basedao.save("t_visitlog", map);
                    //这里进来就判断，没有就去注册
                    //ZZRegist(openid, HttpUtility.UrlDecode(nickname));

                    return View("Index");
                }
                catch (Exception ex)
                {

                    return RedirectToAction("ErrorPage", "WxPage", new { Msg = ex.Message.ToString() });
                }

            }
            else
            {
                //这里表示如果没有的话，就该去引导用户访问微信身份授权页面
                System.Web.HttpContext.Current.Session["code"] = "null";
                return RedirectToAction("WxRequestGetOpenID", "WxRequest", new { ViewPageName = "Index" }); 
            }        
        }





        public ActionResult Mine(string PayImme,string ZZOrderId)
        {
            //PayImme= PayImmediately, ZZOrderId= OrderId
            string result = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];


            if (string.IsNullOrEmpty(result))
            {
                result = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            if (string.IsNullOrEmpty(result))
            {
                result = System.Web.HttpContext.Current.Request.UserHostAddress;
            }
            if (string.IsNullOrEmpty(result))
            {
                result = "0.0.0.0";
            }
            System.Diagnostics.Debug.WriteLine("页面:Mine,本次来的SessionId=" + Session.SessionID + ",time=" + DateTime.Now.ToString() + ",time=" + DateTime.Now.ToString() + ",IP=" + result);
            string OpenId = "";
            string UserName, TelNum, ZZMemberNo;
            if (CheckCookies())
            {
                //会员判断
                Dictionary<string, string> User = new Dictionary<string, string>();
                if (CheckId(Request.Cookies["openid"].Value, out User))
                {
                    OpenId = Request.Cookies["openid"].Value;
                    UserName = User["UserName"];
                    TelNum = User["PhoneNum"];
                    ZZMemberNo = User["ZZMemberNo"];
                }
                else
                {
                    //引导到注册页面
                    return RedirectToAction("Register");
                }
                ViewBag.UserName = UserName;
                ViewBag.HeadImgUrl = Request.Cookies["headimgurl"].Value;
                ViewBag.MemberNo = ZZMemberNo;

                OpenId = Request.Cookies["openid"].Value;

                string sql = " SELECT a.HotelId,a.ZZOrderId,CONVERT(varchar(100),a.OrderTime,120) as OrderTime,c.HotelName,c.RoomTypeName,";
                sql += " CONVERT(varchar(10),a.EnterTime,120)+'   '+datename(weekday,a.EnterTime) as EnterTime,CONVERT(varchar(10),a.LeaveTime,120)+'   '+datename(weekday,a.LeaveTime) as LeaveTime,datediff(day,a.entertime,a.leavetime) as DiffDay,";
                sql += " a.RoomNum,b.PhoneNum,a.TotalPrice,case WHEN a.State=0 THEN '未支付' WHEN a.State=1 THEN '已付款' WHEN a.State=2 THEN '已取消' END as Orderstate,a.State";
                sql += " from t_o_order a INNER JOIN t_m_user b ON a.OpenId=b.OpenId ";
                sql += " INNER JOIN t_m_room c ON a.RoomTypeId=c.roomTypeId";
                sql += " where a.OpenId='" + OpenId + "'";
                sql += " ORDER BY a.OrderTime DESC";
                try
                {
                    List<Dictionary<string, object>> list = basedao.GetList(sql, new string[] { "HotelId", "ZZOrderId", "OrderTime", "HotelName", "RoomTypeName", "EnterTime", "LeaveTime", "DiffDay", "RoomNum", "PhoneNum", "TotalPrice", "Orderstate", "state" });
                    ViewBag.OrderList = list;
                }
                catch (Exception ex)
                {
                    Dictionary<string, object> datalog = new Dictionary<string, object>();
                    datalog.Add("type", int.Parse("0"));
                    datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    datalog.Add("OpID", "0");
                    datalog.Add("OpLog", "order里面错误：" + ex.Message.ToString().Replace("'", "''").Replace(" ", ""));
                    basedao.save("T_LOG", datalog);
                    return RedirectToAction("ErrorPage", "WxPage", new { Msg = "查询订单有误" });
                }
                if (PayImme == "yes")
                {
                    ViewBag.PayImme = PayImme;
                    ViewBag.ZZOrderId = ZZOrderId;
                }
                else
                {
                    ViewBag.PayImme = "no";
                    ViewBag.ZZOrderId = "-1";
                }
                             
                return View("Mine");



                // return View("OrderList");







            }
            else
            {
                //这里表示如果没有的话，就该去引导用户访问微信身份授权页面
                return RedirectToAction("WxRequestGetOpenID", "WxRequest", new { ViewPageName = "Mine" });                ;
            }


        }

        public ActionResult RoomList()
        {
            
            string HotelId = Request.Form["hotelId"] == null ? null : Request.Form["hotelId"].ToString();
            string EnterTime = Request.Form["formETime"] == null ? null : Request.Form["formETime"].ToString();
            string LeaveTime = Request.Form["formLTime"] == null ? null : Request.Form["formLTime"].ToString();

            if (Request.QueryString["hotelid"] != null)
            {
                if(Request.QueryString["hotelid"].ToString()=="210883" || Request.QueryString["hotelid"].ToString() == "209412" || Request.QueryString["hotelid"].ToString() == "210888" || Request.QueryString["hotelid"].ToString() == "210901")
                {
                    HotelId = Request.QueryString["hotelid"].ToString();
                }
            }

            if (HotelId == null)
            {   
                //默认选择的酒店
                HotelId = "210883";
            }


            if (EnterTime==null || LeaveTime == null)
            {
                //这里只判断一天的时间                
                EnterTime = DateTime.Now.ToString("yyyy/MM/dd");
                LeaveTime = DateTime.Now.AddDays(1).ToString("yyyy/MM/dd");
            }
            LeaveTime = DateTime.Parse(LeaveTime).AddDays(-1).ToString("yyyy/MM/dd");

            string[] protype = new string[] { "roomTypeId", "hotelId", "roomTypeName", "Price", "available","hotelName" };
            string sql = "select a.roomTypeId,a.hotelId,a.roomTypeName,a.Price,available,b.hotelName from t_m_roomType a inner join t_m_hotel b on a.hotelid=b.hotelid " +
                " inner join t_m_room c on a.roomTypeId=c.roomTypeId " +
                " where roomdate between '" + EnterTime + "' and '" + LeaveTime + "' and a.hotelId=" + HotelId;
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();                
            list = basedao.GetList(sql, protype);
            List<Dictionary<string, object>> RoomList = new List<Dictionary<string, object>>();

            for (int i = 0; i < list.Count; i++)
            {
                string temp = "";
                double price = 0;
                int available = 0;
                temp = list[i]["roomTypeId"].ToString();
                available = int.Parse(list[i]["available"].ToString());
                price = double.Parse(list[i]["Price"].ToString());
                try
                {
                    //这里把最低的价格选进来
                    if (double.Parse( RoomList.Find(s => s["roomTypeId"].ToString().Equals(temp))["Price"].ToString()) > price)
                    {
                        RoomList.Find(s => s["roomTypeId"].ToString().Equals(temp))["Price"] = price;
                    }
                    //这里把最低的available选进来
                    if(int.Parse(RoomList.Find(s => s["roomTypeId"].ToString().Equals(temp))["available"].ToString()) > available)
                    {
                        RoomList.Find(s => s["roomTypeId"].ToString().Equals(temp))["available"] = available;
                    }

                }
                catch (NullReferenceException)
                {
                    //说明没有相关项目，需要添加进去
                    RoomList.Add(list[i]);
                }
                catch (ArgumentNullException)
                {
                    RoomList.Add(list[i]);
                }
                catch(Exception ex)
                {
                    //ex.ToString();
                }
            }
            //先按照价格排序
            RoomList.Sort(
                delegate(Dictionary<string, object> map1, Dictionary<string, object> map2)
                {
                    if(double.Parse(map1["Price"].ToString()) > double.Parse(map2["Price"].ToString()))
                    {
                        return 1;
                    }
                    else if(double.Parse(map1["Price"].ToString()) == double.Parse(map2["Price"].ToString()))
                    {
                        return 0;
                    }
                    else
                    {
                        return -1;
                    }                        
                }
            );
            //按照可定的房型排序，把不可订的排到后面
            RoomList.Sort(
                delegate (Dictionary<string, object> map1, Dictionary<string, object> map2)
                {
                    if (int.Parse(map1["available"].ToString()) > 0 && int.Parse(map2["available"].ToString()) >0)
                    {
                        return 0;
                    }
                    else if (int.Parse(map1["available"].ToString()) <= 0 && int.Parse(map2["available"].ToString()) > 0 )
                    {
                        //这里要把可定的排在前面，也就是要把map2排靠前，所以要返回map1要比map2大，那么map1就排在后面了，map2就排在前面了
                        return 1;
                    }
                    else if(int.Parse(map1["available"].ToString()) > 0 && int.Parse(map2["available"].ToString()) <= 0)
                    {
                        //这里要把可定的排在前面，也就是要把map1排靠前，所以要返回map1要比map2小，那么map2就排在后面了，map1就排在前面了
                        return -1;
                    }
                    else if(int.Parse(map1["available"].ToString()) <= 0 && int.Parse(map2["available"].ToString()) <= 0)
                    {
                        return 0;
                    }
                    else
                    {
                        //上面4个情况都包含了，该else不会出现，仅仅为了编译成功 和可读性
                        return 0;
                    }
                }
            );
            ViewBag.HotelName = RoomList[0]["hotelName"].ToString();
            ViewBag.List = RoomList;
            ViewBag.EnterTime = EnterTime;// + " (" + Day2Week(EnterTime) + ")";
            ViewBag.LeaveTime = DateTime.Parse(LeaveTime).AddDays(+1).ToString("yyyy/MM/dd");// + " (" + Day2Week(DateTime.Parse(LeaveTime).AddDays(+1).ToString("yyyy/MM/dd")) + ")";
            ViewBag.NightNum = (DateTime.Parse(LeaveTime).AddDays(+1) - DateTime.Parse(EnterTime)).Days;
            if (HotelId == "210883")
            {
                return View("RoomList_SPB");    //返回沙坪坝店
            }
            else if (HotelId == "209412")
            {
                return View("RoomList_BB");     //返回北碚店
            }
            else if (HotelId == "210901")
            {
                return View("RoomList_YGC");     //返回月光城店
            }
            else
            {
                return View("RoomList_WXC");     //返回北碚店
            }


        }

        public ActionResult OrderRoom()
        {
            string OpenId = "";
            string UserName = "";
            string TelNum = "";
            string ZZMemberNo = "";
            Dictionary<string, string> User = new Dictionary<string, string>();
            if (CheckCookies())
            {
                if (CheckId(Request.Cookies["openid"].Value,out User))
                {
                    OpenId = Request.Cookies["openid"].Value;
                    UserName = User["UserName"];
                    TelNum = User["PhoneNum"];
                    ZZMemberNo = User["ZZMemberNo"];
                }
                else
                {
                    //引导到注册页面
                    return RedirectToAction("Register");
                }
            }
            else
            {
                //返回主页
                return RedirectToAction("WxRequestGetOpenID", "WxRequest", new { ViewPageName = "Index" });
            }


            string HotelId = Request.Form["hotelId"] == null ? null : Request.Form["hotelId"].ToString();
            string EnterTime = Request.Form["formETime"] == null ? null : Request.Form["formETime"].ToString();
            string LeaveTime = Request.Form["formLTime"] == null ? null : Request.Form["formLTime"].ToString();
            string roomTypeId = Request.Form["roomTypeId"] == null ? null : Request.Form["roomTypeId"].ToString();

            int RoomNum = 0;
            string RoomName = "";
            HotelId = HotelId ?? "210883";
            List<Dictionary<string,object>>name= basedao.GetList("select hotelName from t_m_hotel where hotelId='" + HotelId + "'", new string[] { "HotelName" });
            string HotelName = "";
            HotelName = name[0]["HotelName"].ToString();
            roomTypeId = roomTypeId ?? "1944";
            if (EnterTime == null || LeaveTime == null)
            {
                //这里只判断一天的时间                
                EnterTime = DateTime.Now.ToString("yyyy/MM/dd");
                LeaveTime = DateTime.Now.AddDays(1).ToString("yyyy/MM/dd");
            }
            DateTime enter = new DateTime();
            DateTime leave = new DateTime();
            if ( !(DateTime.TryParse(EnterTime, out enter) && DateTime.TryParse(LeaveTime,out leave)) )
            {

                return RedirectToAction("ErrorPage", "WxPage", new { Msg = "时间转换错误" });
            }
            //调用住哲函数获取该房型信息
            XmlDocument xml = new XmlDocument();
            ZhuZheAPI ZZAPI = new ZhuZheAPI();
            //警告:该API方法获取数据不正确，需要后续修改
            xml = ZZAPI.FuncAction("zhuzher.room.getMemberRoomPrice",ZZAPI.XmlInput_getMemberRoomPrice(HotelId, roomTypeId,enter,leave));
            if (xml != null && xml.SelectSingleNode("//result/errorMsg").InnerText.Contains("调用成功"))
            {
                int loopdays = 0;double RoomPrice = 0; int avail = 0;
                loopdays = xml.SelectSingleNode("//days").ChildNodes.Count;
                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                for (int i = 0; i < loopdays; i++)
                {
                    string RoomDate = xml.SelectSingleNode("//days").ChildNodes[i]["date"].InnerText;
                    string RoomTypeName = xml.SelectSingleNode("//days").ChildNodes[i].SelectSingleNode("roomTypes/roomType")["roomTypeName"].InnerText;
                    string Available= xml.SelectSingleNode("//days").ChildNodes[i].SelectSingleNode("roomTypes/roomType")["available"].InnerText;
                    string Price= xml.SelectSingleNode("//days").ChildNodes[i].SelectSingleNode("roomTypes/roomType")["fitPrice"].InnerText;

                    if(!(double.TryParse(Price,out RoomPrice) && int.TryParse(Available,out avail)))
                    {
                        return RedirectToAction("ErrorPage", "WxPage", new { Msg = "房间价格或数量转换错误" });
                    }
                    
                    Dictionary<string, object> map = new Dictionary<string, object>()
                    {
                        ["RoomDate"] = RoomDate,
                        ["RoomTypeName"] = RoomTypeName,
                        ["Available"] = avail,
                        ["Price"]=RoomPrice                        
                    };
                    list.Add(map);
                    
                }
                RoomNum=list.Min(u => int.Parse(u["Available"].ToString()));
                RoomName = list[0]["RoomTypeName"].ToString();
                ViewBag.List = list;
            }
            else
            {
                return RedirectToAction("ErrorPage", "WxPage", new { Msg = "调用住哲API查询房型不成功" });
            }
            
            ViewBag.HotelName = HotelName;
            ViewBag.RoomNum = RoomNum <= 0 ? 0 : RoomNum;
            ViewBag.RoomName = RoomName;
            ViewBag.HotelId = HotelId;
            ViewBag.EnterTime = EnterTime;
            ViewBag.LeaveTime = LeaveTime;
            ViewBag.RoomTypeId = roomTypeId;
            ViewBag.NightNum = (DateTime.Parse(LeaveTime) - DateTime.Parse(EnterTime)).Days;
            ViewBag.UserName = UserName;
            ViewBag.TelNum = TelNum;
            ViewBag.ZZMemberNo = ZZMemberNo;
            if(HotelId== "210883")
            {
                return View("OrderRoom_SPB");
            }
            else if(HotelId == "209412")
            {
                return View("OrderRoom_BB");
            }
            else if (HotelId == "210901")
            {
                return View("OrderRoom_YGC");
            }
            else
            {
                return View("OrderRoom_WXC");
            }
            
        }

        [HttpPost]
        public ActionResult Order()
        {
            if (!CheckCookies())
            {
                //这里表示如果没有的话，就该去引导用户访问微信身份授权页面
                return RedirectToAction("WxRequestGetOpenID", "WxRequest", new { ViewPageName = "Index" });                
            }
            string HotelId = Request.Form["HotelId"] == null ? null : Request.Form["HotelId"].ToString();
            string HotelName = Request.Form["HotelName"] == null ? null : Request.Form["HotelName"].ToString();
            string RoomName = Request.Form["RoomName"] == null ? null : Request.Form["RoomName"].ToString();
            string MemberNo = Request.Form["MemberNo"] == null ? null : Request.Form["MemberNo"].ToString();
            string RoomTypeId = Request.Form["RoomTypeId"] == null ? null : Request.Form["RoomTypeId"].ToString();
            string EnterTime = Request.Form["EnterTime"] == null ? null : Request.Form["EnterTime"].ToString();
            string LeaveTime = Request.Form["LeaveTime"] == null ? null : Request.Form["LeaveTime"].ToString();
            string RoomNum = Request.Form["RoomNum"] == null ? null : Request.Form["RoomNum"].ToString();
            string TotalPrice = Request.Form["TotalPrice"] == null ? null : Request.Form["TotalPrice"].ToString();
            string PersonName = Request.Form["PersonName"] == null ? null : Request.Form["PersonName"].ToString();
            string Tel = Request.Form["Tel"] == null ? null : Request.Form["Tel"].ToString();
            string Remark = Request.Form["Remark"] == null ? null : Request.Form["Remark"].ToString();
            string CheckInName = Request.Form["CheckInName"] == null ? null : Request.Form["CheckInName"].ToString();
            string ContactTel = Request.Form["ContactTel"] == null ? null : Request.Form["ContactTel"].ToString();
            string PayImmediately = Request.Form["PayImmediately"] == null ? null : Request.Form["PayImmediately"].ToString();
            //判断数据正确性
            int i_RoomNum = 0;
            double i_TotalPrice = 0;
            if(!int.TryParse(RoomNum,out i_RoomNum))
            {
                return RedirectToAction("ErrorPage", "WxPage", new { Msg = "订单提交，房间数量错误" });
            }
            if(!double.TryParse(TotalPrice,out i_TotalPrice))
            {
                return RedirectToAction("ErrorPage", "WxPage", new { Msg = "订单提交，合计房价错误" });
            }

            //下面开始调用住哲API
            string OrderId = "";
            XmlDocument xml = new XmlDocument();
            ZhuZheAPI ZZAPI = new ZhuZheAPI();
            xml = ZZAPI.FuncAction("zhuzher.member.submitOrder2", ZZAPI.SubmitOrder2(HotelId,MemberNo, i_RoomNum, DateTime.Parse(EnterTime),
                DateTime.Parse(LeaveTime),RoomTypeId, RoomName, TotalPrice, CheckInName, ContactTel, Remark));
            if (xml != null && xml.SelectSingleNode("//result/errorMsg").InnerText.Contains("调用成功"))
            {
                OrderId = xml.SelectSingleNode("//orderId").InnerText;
                Dictionary<string, object> map = new Dictionary<string, object>()
                {
                    ["HotelId"] = HotelId,
                    ["MemberNo"]= MemberNo,
                    ["RoomTypeId"]= RoomTypeId,
                    ["EnterTime"]= EnterTime,
                    ["LeaveTime"]= LeaveTime,
                    ["RoomNum"]= RoomNum,
                    ["TotalPrice"]= TotalPrice,
                    ["PersonName"]= PersonName,
                    ["Tel"]= Tel,
                    ["OpenId"]= Request.Cookies["openid"].Value,
                    ["OrderTime"]=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    ["ZZOrderId"]= OrderId,
                    ["State"]=0,
                    ["Remark"]= Remark
                };
                Dictionary<string, object> WxPrePayMap = new Dictionary<string, object>()
                {
                    ["ZZOrderId"] = OrderId,
                    ["TotalFee"]= TotalPrice,
                    ["State"]=0
                };
                Dictionary<string, object> WxCallBackMap = new Dictionary<string, object>()
                {
                    ["ZZOrderId"] = OrderId
                };
                try
                {
                    basedao.save("t_o_order", map);
                    basedao.save("t_o_WxPrePay", WxPrePayMap);
                    basedao.save("t_o_WxCallBack", WxCallBackMap);
                }
                catch (Exception ex)
                {

                    Dictionary<string, object> datalog = new Dictionary<string, object>();
                    datalog.Add("type", int.Parse("0"));
                    datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    datalog.Add("OpID", "0");
                    datalog.Add("OpLog", "order里面错误：" + ex.Message.ToString().Replace("'", "''").Replace(" ", ""));
                    basedao.save("T_LOG", datalog);
                    return RedirectToAction("ErrorPage", "WxPage", new { Msg = "订单已生成，但保存有误" });
                }


            }
            else
            {
                string ErrorMsg = xml.SelectSingleNode("//result/errorMsg").InnerText;
                return RedirectToAction("ErrorPage", "WxPage", new { Msg = ErrorMsg });
            }
            SMS.SMS_Order(RoomNum, "无隅·" + HotelName + "·" + RoomName, EnterTime, LeaveTime, Tel);
            return RedirectToAction("Mine","WxPage",new { PayImme= PayImmediately, ZZOrderId= OrderId });


        }

        [HttpPost]
        public ActionResult WxPay()
        {
            string ZZOrderId = Request.Form["ZZOrderId"] == null ? null : Request.Form["ZZOrderId"].ToString();
            if (ZZOrderId == null)
            {
                var result = new { err = "errOrderId", Param = "" };
                return Json(result);
            }
            //身份验证
            if (!CheckCookies())
            {
                //这里表示如果没有的话，就该去引导用户访问微信身份授权页面
                var result = new { err = "NoCookies", Param = "" };
                return Json(result);
            }
            else
            {
                Dictionary<string, string> User = new Dictionary<string, string>();
                if (CheckId(Request.Cookies["openid"].Value, out User))
                {
                }
                else
                {
                    var result = new { err = "errId", Param = "" };
                    return Json(result);
                }
            }

            //检查订单号
            string sql = "SELECT top 1 a.OpenId,b.hotelName,b.roomTypeName,a.RoomNum,a.TotalPrice ";
            sql += " FROM t_o_order a INNER JOIN t_m_room b ON a.RoomTypeId=b.roomTypeId AND a.HotelId=b.hotelId ";
            sql += " where a.ZZOrderId='" + ZZOrderId + "'";
            List<Dictionary<string, object>> L_Order = new List<Dictionary<string, object>>();

            //验证订单
            L_Order = basedao.GetList(sql, new string[] { "OpenId", "hotelName", "roomTypeName", "RoomNum", "TotalPrice" });
            if (L_Order.Count != 1)
            {
                //表明有误，直接返回错误
                var result = new { err = "errOrderId", Param = "" };
                return Json(result);
            }

            //下面调起微信支付

            JsApiPay jsApiPay = new JsApiPay();
            jsApiPay.openid = L_Order[0]["OpenId"].ToString();    
            jsApiPay.total_fee =int.Parse((100*double.Parse(L_Order[0]["TotalPrice"].ToString())).ToString());//微信是用“分”作为单位，所以要变换后乘以100
            try
            {
                string GoodsName = "无隅·" + L_Order[0]["hotelName"] + "-" + L_Order[0]["roomTypeName"] + "×" + L_Order[0]["RoomNum"];
                string WxTradeNo = WxPayApi.GenerateOutTradeNo();
                WxPayData unifiedOrderResult = jsApiPay.GetZZOrderResult(GoodsName, ZZOrderId, WxTradeNo);
                //WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult();
                string wxJsApiParam = jsApiPay.GetJsApiParameters();//获取H5调起JS API参数   
                string PrePayId = unifiedOrderResult.GetValue("prepay_id").ToString();
                //更新微信预付款表
                sql = "update t_o_WxPrePay set wxprepayid='" + PrePayId + "',goodsname='" + GoodsName + "',wxtradeno='" + WxTradeNo + "',totalfee='" + jsApiPay.total_fee.ToString() + "',";
                sql += " orderTime='" + DateTime.Now.ToString() + "',state=0 where zzorderid='" + ZZOrderId + "'";
                if (1 != BaseDao.execute(sql))
                {
                    var result = new { err = "WxPayError:更新微信预付款表出错", Param = wxJsApiParam };
                    return Json(result);
                }
                //更新微信回调函数表
                sql = "update t_o_WxCallBack set out_trade_no='" + WxTradeNo + "' where ZZOrderId='" + ZZOrderId + "'";
                if(1!= BaseDao.execute(sql))
                {
                    var result = new { err = "WxPayError:更新微信CallBack函数出错", Param = wxJsApiParam };
                    return Json(result);
                }
                //如果都成功，则正常返回
                var result_ok=new { err = "ok", Param = wxJsApiParam };
                return Json(result_ok);
            

            }
            catch (Exception ex)
            {
                return RedirectToAction("ErrorPage", "WxPage", new { Msg = "查询订单有误" });
                //throw;
            }



        }

        public ActionResult CancelOrder()
        {
            if (!CheckCookies())
            {
                //这里表示如果没有的话，就该去引导用户访问微信身份授权页面
                return RedirectToAction("WxRequestGetOpenID", "WxRequest", new { ViewPageName = "Index" });
            }
            string HotelId = Request.Form["hotelId"] == null ? null : Request.Form["hotelId"].ToString();
            string OrderId = Request.Form["OrderId"] == null ? null : Request.Form["OrderId"].ToString();

            XmlDocument xml = new XmlDocument();
            ZhuZheAPI ZZAPI = new ZhuZheAPI();
            xml = ZZAPI.FuncAction("zhuzher.order.cancleOrderInfo", ZZAPI.CancelOrder(HotelId,OrderId));
            if (xml != null && xml.SelectSingleNode("//result/errorMsg").InnerText.Contains("调用成功"))
            {
                try
                {
                    string sql = "update t_o_order set state=2 where hotelid='" + HotelId + "' and ZZOrderId='" + OrderId + "'";
                    BaseDao.execute(sql);
                    Dictionary<string, object> datalog = new Dictionary<string, object>();
                    datalog.Add("type", int.Parse("0"));
                    datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    datalog.Add("OpID", "0");
                    datalog.Add("OpLog", "用户执行取消订单：" + xml.OuterXml.Replace("'", "''").Replace(" ", ""));
                    basedao.save("T_LOG", datalog);
                }
                catch (Exception ex)
                {
                    Dictionary<string, object> datalog = new Dictionary<string, object>();
                    datalog.Add("type", int.Parse("0"));
                    datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    datalog.Add("OpID", "0");
                    datalog.Add("OpLog", "CancelOrder里面错误：" + ex.Message.ToString().Replace("'", "''").Replace(" ", ""));
                    basedao.save("T_LOG", datalog);
                    
                }
                return Json("1");
            }
            else
            {
                return Json("0");
            }
                
        }



        public ActionResult OrderList()
        {
            if (!CheckCookies())
            {
                //这里表示如果没有的话，就该去引导用户访问微信身份授权页面
                return RedirectToAction("WxRequestGetOpenID", "WxRequest", new { ViewPageName = "Index" });
            }
            string OpenId = Request.Cookies["openid"].Value;

            string sql = " SELECT a.HotelId,a.ZZOrderId,CONVERT(varchar(100),a.OrderTime,120) as OrderTime,c.HotelName,c.RoomTypeName,";
            sql += " CONVERT(varchar(10),a.EnterTime,120) as EnterTime,CONVERT(varchar(10),a.LeaveTime,120) as LeaveTime,datediff(day,a.entertime,a.leavetime) as DiffDay,";
            sql += " a.RoomNum,b.PhoneNum,a.TotalPrice,case WHEN a.State=0 THEN '未支付' WHEN a.State=1 THEN '已付款' WHEN a.State=2 THEN '已取消' END as Orderstate,a.State";
            sql += " from t_o_order a INNER JOIN t_m_user b ON a.OpenId=b.OpenId ";
            sql += " INNER JOIN t_m_room c ON a.RoomTypeId=c.roomTypeId";
            sql += " where a.OpenId='" + OpenId + "'";
            sql += " ORDER BY a.OrderTime DESC";
            try
            {
                List<Dictionary<string, object>> list = basedao.GetList(sql, new string[] { "HotelId", "ZZOrderId", "OrderTime", "HotelName", "RoomTypeName", "EnterTime", "LeaveTime", "DiffDay", "RoomNum", "PhoneNum", "TotalPrice", "Orderstate", "state" });
                ViewBag.OrderList = list;
            }
            catch (Exception ex)
            {
                Dictionary<string, object> datalog = new Dictionary<string, object>();
                datalog.Add("type", int.Parse("0"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", "0");
                datalog.Add("OpLog", "order里面错误：" + ex.Message.ToString().Replace("'", "''").Replace(" ", ""));
                basedao.save("T_LOG", datalog);
                return RedirectToAction("ErrorPage", "WxPage", new { Msg = "查询订单有误" });
            }
            




            return View("OrderList");

        }


        public ActionResult Register()
        {
            if (CheckCookies())
            {
                return View("Register");
            }
            else
            {
                //这里表示如果没有Cookies的话，就该去引导用户访问微信身份授权页面
                return RedirectToAction("WxRequestGetOpenID", "WxRequest", new { ViewPageName = "Register" });
            }
        }


        public ActionResult UserEdit()
        {
            if (CheckCookies())
            {
                return View("UserEdit");
            }
            else
            {
                //这里表示如果没有Cookies的话，就该去引导用户访问微信身份授权页面
                return RedirectToAction("WxRequestGetOpenID", "WxRequest", new { ViewPageName = "Register" });
            }
        }

        [HttpPost]
        public ActionResult SMSRegister()
        {//ajax方式上来
            //数据库内，已经把UserName和PhoneNum设置为联合主键
            //获取微信OpenId
            string OpenId = "";
            if (CheckCookies())
            {
                //正常，什么都不做
                OpenId = Request.Cookies["openid"].Value;
            }
            else
            {
                //返回cookies获取失败
                return Json("4");
            }
            
            string ClientName = Request.Form["ClientName"] ?? "";
            string PhoneNum = Request.Form["PhoneNum"] ?? "";
            if(ClientName == "" || PhoneNum == "")
            {
                return Json("0");
            }
            string VerifyNum = GenerateVerifyNum(4);
            string[] protype = { "UserId","openid","RegTime","Username","PhoneNum","validate" };
            List<Dictionary<string, object>> list = basedao.findMapByProperties("t_m_user", protype, "openid='" + OpenId + "' and PhoneNum='" + PhoneNum + "'");
            if (list.Count < 1)
            {//表明我的数据库里面没有该人员信息
                //这里还需要做相应的添加操作住哲会员操作
                //首先判断住哲里面是不是有这个手机号
                string MemberNo = "";
                XmlDocument xml = new XmlDocument();
                ZhuZheAPI ZZAPI = new ZhuZheAPI();

                xml = ZZAPI.FuncAction("zhuzher.member.getMemberNoByInfo",ZZAPI.GetMemberNo(PhoneNum));
                if (xml != null && xml.SelectSingleNode("//result/errorMsg").InnerText.Contains("调用成功"))
                {//表明住哲里面有这个手机号的会员
                    MemberNo = xml.SelectSingleNode("//memberCardNo").InnerText;
                    Dictionary<string, object> AddUserInfoMap = new Dictionary<string, object>()
                    {
                        ["OpenId"] = OpenId,
                        ["headimgurl"]= Request.Cookies["headimgurl"].Value,
                        ["RegTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                        ["VerifyNum"] = VerifyNum,
                        ["UserName"] = ClientName,
                        ["PhoneNum"] = PhoneNum,
                        ["validate"] = "1",
                        ["ZZMemberNo"] = MemberNo
                    };
                    //加入数据库里面
                    basedao.save("t_m_user", AddUserInfoMap);

                }
                else if(xml!=null && xml.SelectSingleNode("//result/errorMsg").InnerText.Contains("没有找到任何相关会员信息"))
                {
                    //说明住哲里面没有该会员，先不添加MemberNo的值进来
                    Dictionary<string, object> AddUserInfoMap = new Dictionary<string, object>()
                    {
                        ["OpenId"] = OpenId,
                        ["headimgurl"] = Request.Cookies["headimgurl"].Value,
                        ["RegTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                        ["VerifyNum"] = VerifyNum,
                        ["UserName"] = ClientName,
                        ["PhoneNum"] = PhoneNum,
                        ["validate"] = "0"
                    };
                    //加入数据库里面
                    basedao.save("t_m_user", AddUserInfoMap);
                }
                else
                {
                    return Json("0");
                }               
            }
            else if (list.Count == 1)
            {
                //表明现在需要重发验证码，所以添加上次发送验证码的时间判断
                //阿里云的流控规则为 1分钟间隔 1个小时向同一手机不会多余5条，1天不会多余40条
                TimeSpan TS = DateTime.Now - DateTime.Parse(list[0]["RegTime"].ToString());
                if (60 > TS.TotalSeconds)
                {
                    //表示还没到60秒时间，属于非法提交了
                    return Json("2");
                }
            }
            //更新注册时候的验证码和时间
            string sql = "update t_m_user set verifyNum='" + VerifyNum + "',RegTime='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where PhoneNum='" + PhoneNum + "'";
            BaseDao.execute(sql);

            SMS.SMS_Login(VerifyNum, PhoneNum);
            return Json("1");
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SMSSend_UserEdit()
        {
            string OpenId = "";
            if (CheckCookies())
            {
                //正常，什么都不做
                OpenId = Request.Cookies["openid"].Value;
            }
            else
            {
                //返回cookies获取失败
                return Json("4");
            }

            string ClientName = Request.Form["ClientName"] ?? "";
            string PhoneNum = Request.Form["PhoneNum"] ?? "";
            if (ClientName == "" || PhoneNum == "")
            {
                return Json("0");
            }
            string VerifyNum = GenerateVerifyNum(4);
            string[] protype = { "UserId", "openid", "RegTime", "Username", "PhoneNum", "validate" };
            List<Dictionary<string, object>> list = basedao.findMapByProperties("t_m_user", protype, "openid='" + OpenId+"'");
            if (list.Count < 1)
            {//表明我的数据库里面没有该人员信息
                //这里还需要做相应的添加操作住哲会员操作
                //首先判断住哲里面是不是有这个手机号
                string MemberNo = "";
                XmlDocument xml = new XmlDocument();
                ZhuZheAPI ZZAPI = new ZhuZheAPI();

                xml = ZZAPI.FuncAction("zhuzher.member.getMemberNoByInfo", ZZAPI.GetMemberNo(PhoneNum));
                if (xml != null && xml.SelectSingleNode("//result/errorMsg").InnerText.Contains("调用成功"))
                {//表明住哲里面有这个手机号的会员
                    MemberNo = xml.SelectSingleNode("//memberCardNo").InnerText;
                    Dictionary<string, object> AddUserInfoMap = new Dictionary<string, object>()
                    {
                        ["OpenId"] = OpenId,
                        ["headimgurl"] = Request.Cookies["headimgurl"].Value,
                        ["RegTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                        ["VerifyNum"] = VerifyNum,
                        ["UserName"] = ClientName,
                        ["PhoneNum"] = PhoneNum,
                        ["validate"] = "1",
                        ["ZZMemberNo"] = MemberNo
                    };
                    //加入数据库里面
                    basedao.save("t_m_user", AddUserInfoMap);

                }
                else if (xml != null && xml.SelectSingleNode("//result/errorMsg").InnerText.Contains("没有找到任何相关会员信息"))
                {
                    //说明住哲里面没有该会员，先不添加MemberNo的值进来
                    Dictionary<string, object> AddUserInfoMap = new Dictionary<string, object>()
                    {
                        ["OpenId"] = OpenId,
                        ["headimgurl"] = Request.Cookies["headimgurl"].Value,
                        ["RegTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                        ["VerifyNum"] = VerifyNum,
                        ["UserName"] = ClientName,
                        ["PhoneNum"] = PhoneNum,
                        ["validate"] = "0"
                    };
                    //加入数据库里面
                    basedao.save("t_m_user", AddUserInfoMap);
                }
                else
                {
                    return Json("0");
                }
            }
            else if (list.Count == 1)
            {
                //表明现在需要重发验证码，所以添加上次发送验证码的时间判断
                //阿里云的流控规则为 1分钟间隔 1个小时向同一手机不会多余5条，1天不会多余40条
                TimeSpan TS = DateTime.Now - DateTime.Parse(list[0]["RegTime"].ToString());
                if (60 > TS.TotalSeconds)
                {
                    //表示还没到60秒时间，属于非法提交了
                    return Json("2");
                }
            }
            //更新注册时候的验证码和时间
            string sql = "update t_m_user set verifyNum='" + VerifyNum + "',RegTime='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where openid='" + OpenId + "'";
            BaseDao.execute(sql);

            SMS.SMS_Login(VerifyNum, PhoneNum);
            return Json("1");
        }

        /// <summary>
        /// 验证码提交验证
        /// </summary>
        /// <returns></returns>
        public ActionResult VerifyCode()
        {
            if (CheckCookies())                
            {
                string OpenId = Request.Cookies["openid"].Value;
                string headimgurl = Request.Cookies["headimgurl"].Value;
                string Code = Request.Form["VerifyNum"] ?? "";
                string PhoneNum = Request.Form["PhoneNum"] ?? "";
                string UserName = Request.Form["ClientName"] ?? "";
                string[] protype = { "UserId", "RegTime", "Username", "PhoneNum", "validate","VerifyNum","ZZMemberNo" };
                List<Dictionary<string, object>> list = basedao.findMapByProperties("t_m_user", protype, "PhoneNum='" + PhoneNum + "'");
                if(list.Count<1)
                {
                    //表明没有搜索到用户，让前台提示用户名，手机号错误 
                    return Json("2");
                }
                else if (list.Count == 1)
                {
                    TimeSpan TS = DateTime.Now - DateTime.Parse(list[0]["RegTime"].ToString());
                
                    if (15 > TS.TotalMinutes)
                    {
                        if (Code == list[0]["VerifyNum"].ToString())  
                        {
                            //表明操作正确  需要再判断是否添加到住哲会员里面
                            if(list[0]["validate"].ToString()=="0" && list[0]["ZZMemberNo"].ToString() == "")
                            {//表明住哲里面没有该会员需要注册
                                string MemberNo = "";
                                XmlDocument xml = new XmlDocument();
                                ZhuZheAPI ZZAPI = new ZhuZheAPI();
                                xml = ZZAPI.FuncAction("zhuzher.member.registerMember", ZZAPI.RegisterMember(UserName,PhoneNum));
                                if (xml != null && xml.SelectSingleNode("//result/errorMsg").InnerText.Contains("调用成功"))
                                {//表明住哲里面有这个手机号的会员
                                    MemberNo = xml.SelectSingleNode("//memberCardNo").InnerText;
                                }
                                else
                                {
                                    return Json("0");
                                }
                                string sql = "update t_m_user set validate=1,ZZMemberNo='"+MemberNo+"' where PhoneNum = '" + PhoneNum + "'";
                                try
                                {
                                    BaseDao.execute(sql);
                                    return Json("1");
                                }
                                catch (Exception ex)
                                {

                                    Dictionary<string, object> datalog = new Dictionary<string, object>();
                                    datalog.Add("type", int.Parse("0"));
                                    datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                    datalog.Add("OpID", "0");
                                    datalog.Add("OpLog", "VerifyCode里面错误：" + ex.Message.ToString().Replace("'", "''").Replace(" ", ""));
                                    basedao.save("T_LOG", datalog);
                                }

                                

                            }
                            else
                            {//表明注册好了的只需要登录了
                                return Json("1");

                            }
                        }
                        else
                        {
                            //表明验证码错误
                            return Json("4");
                        }              
                    }
                    else
                    {                   
                        //验证码过期
                        return Json("3");
                    }
                }
                return Json("0");                
            }
            else
            {
                //表明没获取到cookies
                return Json("5");
            }


        }

        public ActionResult VerifyCode_UserEdit()
        {
            if (CheckCookies())
            {
                string OpenId = Request.Cookies["openid"].Value;
                string headimgurl = Request.Cookies["headimgurl"].Value;
                string Code = Request.Form["VerifyNum"] ?? "";
                string PhoneNum = Request.Form["PhoneNum"] ?? "";
                string UserName = Request.Form["ClientName"] ?? "";
                string[] protype = { "UserId", "RegTime", "Username", "PhoneNum", "validate", "VerifyNum", "ZZMemberNo" };
                List<Dictionary<string, object>> list = basedao.findMapByProperties("t_m_user", protype, "OpenId='" + OpenId + "'");
                if (list.Count < 1)
                {
                    //表明没有搜索到用户，让前台提示用户名，手机号错误 
                    return Json("2");
                }
                else if (list.Count == 1)
                {
                    TimeSpan TS = DateTime.Now - DateTime.Parse(list[0]["RegTime"].ToString());

                    if (15 > TS.TotalMinutes)
                    {
                        


                        if (Code == list[0]["VerifyNum"].ToString())
                        {

                            //这里直接更新电话和名称
                            string sql = "update t_m_user set UserName='" + UserName + "',PhoneNum='"+ PhoneNum+ "' where OpenId = '" + OpenId + "'";
                            try
                            {
                                BaseDao.execute(sql);
                                return Json("1");
                            }
                            catch (Exception ex)
                            {

                                Dictionary<string, object> datalog = new Dictionary<string, object>();
                                datalog.Add("type", int.Parse("0"));
                                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                datalog.Add("OpID", "0");
                                datalog.Add("OpLog", "VerifyCode里面错误：" + ex.Message.ToString().Replace("'", "''").Replace(" ", ""));
                                basedao.save("T_LOG", datalog);
                            }
                        }
                        else
                        {
                            //表明验证码错误
                            return Json("4");
                        }
                    }
                    else
                    {
                        //验证码过期
                        return Json("3");
                    }
                }
                return Json("0");
            }
            else
            {
                //表明没获取到cookies
                return Json("5");
            }
        }

        /// <summary>
        /// Length是输入产生验证码的个数
        /// </summary>
        /// <param name="Length"></param>
        /// <returns></returns>
        private static string GenerateVerifyNum(int Length)
        {
            char[] constant = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
            System.Text.StringBuilder newRandom = new System.Text.StringBuilder(10);
            Random rd = new Random();
            for (int i = 0; i < Length; i++)
            {
                newRandom.Append(constant[rd.Next(10)]);
            }
            return newRandom.ToString();
        }

        private bool CheckCookies()
        {
            
            if (
                    System.Web.HttpContext.Current.Request.Cookies["openid"] != null && System.Web.HttpContext.Current.Request.Cookies["headimgurl"] != null && System.Web.HttpContext.Current.Request.Cookies["nickname"] != null
                )
                if (System.Web.HttpContext.Current.Request.Cookies["openid"].Value != "" &&  System.Web.HttpContext.Current.Request.Cookies["nickname"].Value != "")
                {
                    Response.Cookies["openid"].Value = Request.Cookies["openid"].Value;
                    Response.Cookies["openid"].Expires = DateTime.Now.AddMonths(12);
                    Response.Cookies["headimgurl"].Value = Request.Cookies["headimgurl"].Value;
                    Response.Cookies["headimgurl"].Expires = DateTime.Now.AddMonths(12);
                    Response.Cookies["nickname"].Value = Request.Cookies["nickname"].Value;
                    Response.Cookies["nickname"].Expires = DateTime.Now.AddMonths(12);
                    System.Diagnostics.Debug.WriteLine("检测到cookies正确，openid="+ Request.Cookies["openid"].Value+"nickname="+ Response.Cookies["nickname"].Value);
                    return true;
                }
            System.Diagnostics.Debug.WriteLine("检测到cookies不对,"+Request.Cookies.Count.ToString());
            return false;            
        }

        /// <summary>
        /// 判断会员
        /// </summary>
        /// <returns></returns>
        private bool CheckId(string OpenId,out Dictionary<string,string> UserInfo)
        {
            int m = 0;
            //判断是否存在该ID
            string[] protype = new string[] { "OpenId", "UserName", "PhoneNum","ZZMemberNo" };
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            try
            {
                list = basedao.findMapByProperties("t_m_user", protype, "openid='" + OpenId + "' and validate=1");
            }
            catch (Exception ex)
            {
                Dictionary<string, object> datalog = new Dictionary<string, object>();
                datalog.Add("type", int.Parse("0"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", "0");
                datalog.Add("OpLog", "ChekId里面：" + ex.Message.ToString().Replace("'", "''").Replace(" ", ""));
                basedao.save("T_LOG", datalog);
            }
            if (list.Count==1)
            {
                Dictionary<string, string> map = new Dictionary<string, string>()
                {
                    ["OpenId"] = OpenId,
                    ["UserName"] = list[0]["UserName"].ToString(),
                    ["PhoneNum"] = list[0]["PhoneNum"].ToString(),
                    ["ZZMemberNo"] = list[0]["ZZMemberNo"].ToString()

                };
                UserInfo = map;
                return true;
            }
            else
            {
                UserInfo = null;
                return false;
            }


        }

        /// <summary>
        /// 住哲注册会员
        /// </summary>
        /// <param name="cookie"></param>
        /// <returns>成功返回“success”，失败返回“error”,已注册返回“registed”</returns>
        public string ZZRegist(string OpenId,string NickName)
        {
            //数据库查询cookie是否已经是会员
            string validate = basedao.GetString("t_m_user", "validate", "and OpenId='" + OpenId + "'");
            if (validate != "1")
            {//执行注册流程
                string MemberNo = "";
                XmlDocument xml = new XmlDocument();
                ZhuZheAPI ZZAPI = new ZhuZheAPI();
                xml = ZZAPI.FuncAction("zhuzher.member.registerMember", ZZAPI.RegisterMember(NickName, ""));
                if (xml != null && xml.SelectSingleNode("//result/errorMsg").InnerText.Contains("调用成功"))
                {//表明住哲里面有这个手机号的会员
                    MemberNo = xml.SelectSingleNode("//memberCardNo").InnerText;
                    Dictionary<string, object> map = new Dictionary<string, object>()
                    {
                        ["OpenId"] = OpenId,
                        ["UserName"] = NickName,
                        ["validate"] = 1,
                        ["ZZMemberNo"] = MemberNo,
                        ["RegTime"] = DateTime.Now.ToString(),
                    };
                    basedao.save("t_m_user", map);
                    return "success";

                }
                else
                {
                    return "error";
                }
            }
            return "registed";
        }



        private string Day2Week(string day)
        {
            string week;
            DateTime dt = DateTime.Parse(day);
            week=dt.DayOfWeek.ToString();
            switch (week)
            {
                case "Monday":
                    week = "星期一";
                    break;
                case "Tuesday":
                    week = "星期二";
                    break;
                case "Wednesday":
                    week = "星期三";
                    break;
                case "Thursday":
                    week = "星期四";
                    break;
                case "Friday":
                    week = "星期五";
                    break;
                case "Saturday":
                    week = "星期六";
                    break;
                case "Sunday":
                    week = "星期日";
                    break;
            }
            return week;
        }
    }
}